"""
商品仓库:本地读取,需要有删除和保存的操作

"""
import os.path
import pickle
from goods import Goods

#书写单例装饰器
def singleton(cls):
    instance = None
    def get_instance(*args,**kwargs):
        nonlocal instance
        if not instance:
            instance = cls(*args, **kwargs)  # 调用__init__
        return instance
    return get_instance

path = r'data/goodslist.txt'

@singleton
class Storage():
    __slots__ = ('goods_list',)
    def __init__(self):
        self.goods_list = None
        self.load_goods()


    def load_goods(self):
        # 商品文件不存在则定义商品列表

        if os.path.exists(path):
            self.get_goods()


        else:
            self.goods_list = []

            goods_info = [['food',19,100],['PC',10000,1],['mouse',100,10],['keyboard',100,10],['phone',1000,10]]

            for sublist in goods_info:
                goods = Goods(name=sublist[0],gprice=sublist[1],balance=sublist[2])
                self.goods_list.append(goods)

                self.save_goods()

    def save_goods(self):
        with open(path,'wb') as f:
            pickle.dump(self.goods_list,f)

    def get_goods(self):
        with open(path, 'rb') as f:
            self.goods_list = pickle.load(f)
        return self.goods_list